local _, ns = ...
local oUF = oUF or ns.oUF

if not oUF then return end
-- based on oUF_GCD by Exactly.

-- Updated by Label to work without spell.


local OnUpdateGCD = function(self)
	local perc = (GetTime() - self.starttime) / self.duration
	if perc > 1 then
		self:Hide()
	else
		if(self.Spark) then
			self.Spark:SetPoint("CENTER", self, "LEFT", perc * self:GetWidth(), 0)
		end
	end
end


local OnHideGCD = function(self)
 	self:SetScript('OnUpdate', nil)
end


local OnShowGCD = function(self)
	self:SetScript('OnUpdate', OnUpdateGCD)
end


local Update = function(self, event, unit, spell)
	if self.GCD and unit == "player" then
		if spell == nil then
			return
		end

		local start, dur = GetSpellCooldown(spell)


		if (not start) then return end
		if (not dur) or dur > 1.5 then return end
		if (dur == 0) then
			self.GCD:Hide()
		else
			self.GCD.starttime = start
			self.GCD.duration = dur
			self.GCD:Show()
		end
	end
end


local Enable = function(self)
	if (self.GCD) then
		self.GCD:Hide()
		self.GCD.starttime = 0
		self.GCD.duration = 0
		
		local spark = self.GCD.Spark
		if(spark and spark:IsObjectType'Texture' and not spark:GetTexture()) then
			spark:SetTexture[[Interface\CastingBar\UI-CastingBar-Spark]]
		end

		self:RegisterEvent("UNIT_SPELLCAST_START", Update)
		self:RegisterEvent("UNIT_SPELLCAST_SUCCEEDED", Update)
		self:RegisterEvent("UNIT_SPELLCAST_INTERRUPTED", Update)
		self.GCD:SetScript('OnHide', OnHideGCD)
		self.GCD:SetScript('OnShow', OnShowGCD)
	end
end


local Disable = function(self)
	if (self.GCD) then
		self:UnregisterEvent('ACTIONBAR_UPDATE_COOLDOWN')
		self.GCD:Hide()
	end
end


oUF:AddElement('GCD', Update, Enable, Disable)
